/*
 * @Author: your name
 * @Date: 2020-10-30 08:18:34
 * @LastEditTime: 2021-04-13 11:08:58
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \zhcg-zhqh\src\permission.js
 */

// 路由跳转到该页面，进行相应的路由守卫拦截
import router from "./router";
import store from "./store";

import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
NProgress.configure({ showSpinner: false }); // NProgress Configuration

import axios from "axios";
import { AJAX_PATH } from "@/services/config.js";
// import { CommonAjax } from "@/services/modules/common.js";
// const commonAjax = new CommonAjax();

const whiteList = [
  "/login",
  "/home",
  "/NoPermission",
  "/ServerError",
  "/personalCenter",
  "/NoExistent",
  "/getToken",
  "/handler"
]; // 没有重定向的白名单列表

const LoginList = ["/login"];

let tag = false;

router.beforeEach(async (to, from, next) => {
  NProgress.start();

  //如果是这两个路由直接跳转，不用鉴权
  if(to.path ==="/handler" || to.path ==="/getToken" || to.path ==="/bind" || to.path ==="/unbind"){
    next();
    return;
  } 
  const Token = localStorage.getItem("zhqh-pro-token");

  console.log("==========路由跳转==============>",to.path);
  // 如果存在 token 的话
  if (Token) {
    // 如果token 存在并且没有过期的话,就跳转到首页,否则不会进行跳转。
    if (await judgeToken()) {
      getMenuRights(Token);

      // 路由鉴权,鉴权完毕后可进行路由跳转。
      if (whiteList.some((item) => item == to.path)) {
        // 需要跳转的路由是否是whiteList中的路由，若是，则直接条状
        next();
      } else if ((await judgePermission(to.path)) == true) {
        next();
      } else {
        next({ path: "/NoPermission" });
      }
    } else {
      localStorage.removeItem("zhqh-pro-token");
      this.$router.push("/login");
    }
    // 没Token 重新跳转到登陆页面
  } else {
    if (LoginList.indexOf(to.path) !== -1) {
      // 需要跳转的路由是否是whiteList中的路由，若是，则直接条状
      next();
    } else {
      next({ path: "/login" });
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});

// 判断token 是否过期
async function judgeToken() {
  const token = JSON.parse(localStorage.getItem("zhqh-pro-token"));
  return new Promise((resolve) => {
    axios.get(AJAX_PATH.checkToken + `?token=${token}`).then((res) => {
      resolve(res.data.result);
    });
  });
}

//  利用路由菜单鉴权,route为要跳转过去的路径,Tree为已经存在的路径
async function judgePermission(path) {
  tag = false;
  isInMenu(path, store.state.user.MenuRights);
  return new Promise((resolve) => {
    resolve(tag);
  });
}

// 是否在路由菜单里
function isInMenu(route, Tree) {
  Tree.forEach((item) => {
    if (item.path == route) {
      tag = true;
    }
    if (item.children && item.children.length != 0) {
      isInMenu(route, item.children);
    }
  });
}

// 获取路由菜单权限
function getMenuRights(token_url) {
  if (token_url != null) {
    // 获取请求
    // commonAjax.getUserRightsByToken(token_url).then((res) => {
    //   if (res.success) {
    //     let menu = [];
    //     for (let i = 0; i < res.result.menu[0].children.length; i++) {
    //       menu.push(res.result.menu[0].children[i]);
    //     }
    //     reduceRoutesFormat(newRouterReduce.children, menu); // 处理完后的整个路由菜单
    //       router.addRoutes([newRouterReduce]);
    //   }
    // });
  }
}
